package cn.kgc.controller;

import cn.kgc.config.WxConfig;
import cn.kgc.dto.Dto;
import cn.kgc.dto.DtoUtil;
import cn.kgc.exception.UserErrorCode;
import cn.kgc.service.WxService;
import cn.kgc.utils.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api")
@Slf4j
public class WxController {

    @Autowired
    WxConfig wxConfig;

    @Autowired
    WxService wxService;

    /**
     * 重定向到微信的扫一扫界面
     *
     * @param httpServletResponse
     * @throws IOException
     * @return
     */
    @RequestMapping("/p/vendors/wechat/login")
    public void wxLogin(HttpServletResponse httpServletResponse) throws IOException {
        StringBuffer urlStringBuffer=new StringBuffer("https://open.weixin.qq.com/connect/qrconnect?appid=");
        urlStringBuffer.append(wxConfig.getAppid());
        urlStringBuffer.append("&redirect_uri=");
        urlStringBuffer.append(URLEncoder.encode("http://localhost:8160/api/callback"));
        urlStringBuffer.append("&response_type=code&scope=snsapi_login&state=dm#wechat_redirect");
        String url=urlStringBuffer.toString();
        httpServletResponse.sendRedirect(url);
    }

    @RequestMapping("/callback")
    public Dto loginCallback(String code,String state) throws Exception {
        log.info("微信回调code:{},state:{}",code,state);
        if(state!=null&&!state.equals("dm")){
            throw new BaseException(UserErrorCode.INVLIDE_REQ);
        }

        return wxService.wxlogin(code);
    }

}
